#include <jni.h>

#include "common.h"
#include "haptimap.h"
#include "haptimap_android2.h"

jint Java_org_haptimap_HaptiMap_SensorInquire(JNIEnv *env, jobject thiz, jobject type, jintArray ptr_count) {
	hm_t *hm = GET_HM(thiz);

	int count;
	if(hm_sensor_inquire(hm, GET_ORDINAL(type), &count) != HM_SUCCESS)
		return HM_FAILURE;

	STORE_INT(ptr_count, count);

	return HM_SUCCESS;
}
jint Java_org_haptimap_HaptiMap_SensorGetId(JNIEnv *env, jobject thiz, jobject type, jint n, jintArray ptr_count) {
	hm_t *hm = GET_HM(thiz);
	int id;

	if(hm_sensor_get_id(hm, GET_ORDINAL(type), n, &id) != HM_SUCCESS)
		return HM_FAILURE;

	STORE_INT(ptr_count, id);

	return HM_SUCCESS;
}
jint Java_org_haptimap_HaptiMap_SensorGetAttribute(JNIEnv *env, jobject thiz, jint id, jobject att, jintArray ptr_val) {
	hm_t *hm = GET_HM(thiz);
	int val;

	if(hm_sensor_get_attribute(hm, id, GET_ORDINAL(att), &val) != HM_SUCCESS)
		return HM_FAILURE;

	STORE_INT(ptr_val, val);

	return HM_SUCCESS;
}
jint Java_org_haptimap_HaptiMap_SensorGetAttributeMultiple(JNIEnv *env, jobject thiz, jint id, jobject att, jintArray ptr_vals) {
	hm_t *hm = GET_HM(thiz);
	int vals[3];
	int count;

	if(hm_sensor_get_attribute_multiple(hm , id, GET_ORDINAL(att), vals, &count) != HM_SUCCESS)
		return HM_FAILURE;

	(*env)->SetIntArrayRegion(env, ptr_vals, 0, count, vals);

	return HM_SUCCESS;
}
jint Java_org_haptimap_HaptiMap_SensorGetAttributeString(JNIEnv *env, jobject thiz, jint id, jobject att, jobject str_val) {
	hm_t *hm = GET_HM(thiz);
	const char *val;
	jstring str;

	if(hm_location_sensor_get_attribute_string(hm, id, GET_ORDINAL(att), &val) != HM_SUCCESS)
		return HM_FAILURE;

	str = (*env)->NewStringUTF(env, val);
 	(*env)->CallObjectMethod(env, str_val, 
		(*env)->GetMethodID(env, (*env)->GetObjectClass(env, str_val),
		"append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;"),
		str);

	(*env)->ReleaseStringUTFChars(env, str, val);

	return HM_SUCCESS;
}
jint Java_org_haptimap_HaptiMap_SensorInitialise(JNIEnv *env, jobject thiz, jint id) {
	hm_t *hm = GET_HM(thiz);

	return hm_sensor_init(hm, id);
}
jint Java_org_haptimap_HaptiMap_SensorUninitialise(JNIEnv *env, jobject thiz, jint id) {
	hm_t *hm = GET_HM(thiz);

	return hm_sensor_uninit(hm, id);
}
jint Java_org_haptimap_HaptiMap_SensorDefineCallback(JNIEnv *env, jobject thiz, jint id, jobject event, jobject cb_interface) {
 	hm_t *hm = GET_HM(thiz);

 	return hm_sensor_callback_define(hm, id, GET_ORDINAL(event), hm_jni_callback_wrapper, 
		(*env)->NewGlobalRef(env, cb_interface)); //FIXME: leaking ref

}
jint Java_org_haptimap_HaptiMap_SensorCancelCallback(JNIEnv *env, jobject thiz, jint id, jobject event) {
	hm_t *hm = GET_HM(thiz);

	/* There will be a memory leak here as we don't delete the global reference to the
	* callback interface class. */
	return hm_sensor_callback_cancel(hm, id, GET_ORDINAL(event));
}
